<?php

namespace app\api\service\template;
use app\api\model\template\Send;
use app\api\model\template\User;
use app\lib\exception\template\TemplateException;
use app\lib\template\Template;
use think\Db;
use think\Exception;
use think\facade\Log;

class TemplateService extends Template
{
    public static $instance;

    public static function getInstance(): TemplateService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getTemplate(){
       $list = $this->template_list();
       foreach ($list as &$item){
           $result = array();
           preg_match_all("/{{(.*)\.DATA}}/",$item['content'], $result);
           $item['data'] = $result[1];
       }
       return $list;
    }

    public function verification(){
      $echoStr = $this->valid();
      return $echoStr;
    }

    public function subscribe(){
        $postObj = $this->responseMsg();
        if (!empty($postObj)){
            $openid = trim($postObj->FromUserName);
            $event = trim($postObj->Event);
            $user = User::where('openid',$openid)->find();
            //开启事务
            Db::startTrans();
            try {
                if ($user) {
                    //修改关注、取消关注状态
                    if ($event == 'subscribe'){
                        $user->subscribe = 1;
                        $user->save();
                    }
                    if ($event == 'unsubscribe') {
                        $user->subscribe = 0;
                        $user->save();
                    }

                } else {
                        //获取accountToken
                         $access_token = $this->getAccessToken();
                         if (!empty($access_token)){
                             //获取用户信息
                             $users = $this->getUser($access_token, $openid);
                             $data = \GuzzleHttp\json_decode($users, true) ?? [];
                             $user = User::where('unionid',$data['unionid'])->findOrEmpty();
                             if ($user->isEmpty()){
                                 User::create($data);
                             }else{
                                 $user->save(['openid'=>$data['openid'],'subscribe'=>$data['subscribe']]);
                             }
                         }
                }
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
            }
        }
        return true;
    }

    public function getFollowUsers(){
       $user = User::where('subscribe',1)
           ->field('id,openid,nickName')
           ->select();
       return $user;
    }

    public function pushTemplate($params){
//        $openid = $params['openid'];
//        if (!is_array($openid)){
//            $openid = \GuzzleHttp\json_decode($openid,true);
//        }
//        $data = $params['data'];
//        if (!is_array($data)){
//            $data = \GuzzleHttp\json_decode($data,true);
//        }
        $template_id = "qtDlJSwv_nffevJ34hhP78D6bngfqi0WWhEHIVpW27s";
        $url = '';
        $miniprogram = [];
//        if (!empty($params['miniprogram'])){
//            $miniprogram = $params['miniprogram'];
//        }
        //模板
        $template = $this->template_list();
        $template_content = "";
        foreach ($template as $item){
            if ($item['template_id'] == $template_id){
                $template_content = $item['content'];
                break;
            }
        }
        //模板不存在
        if (!$template_content){
            throw new TemplateException(['msg'=>'消息模板不存在']);
        }
        $data = [
            "thing11" => $params["message"],
            "time4"=> date("Y-m-d H:i:s",time())
        ];
        foreach ($data as $key=>$item){
            $template_content = str_replace("{{".$key.'.DATA}}',$item,$template_content);
            $data[$key] = ['value'=>$item];
        }
        $openid = User::field("openid")->where("qr_scene",1)->select()->toArray();
        //获取accountToken
        $access_token = $this->getAccessToken();
        if ($access_token){
            foreach ($openid as $item){
                $result = $this->doSend($item["openid"],$template_id,$url,$data,$access_token,$miniprogram);
                $send_arr = [
                    "openid"=>$item["openid"],
                    "template_id"=>$template_id,
                    "content"=>$template_content,
                    "errcode"=>$result['errcode'],
                    "errmsg"=>$result['errmsg']
                ];
                Send::create($send_arr);
            }
        }
        return true;
    }

    public function pushTagTemplate($params){

        $template_id = "3usWLqsDf48PXv3AEon0wm9ag6zylkIr_pRR9nRv2Ps";
        $url = '';
        $miniprogram = [];

        //模板
        $template = $this->template_list();
        $template_content = "";
        foreach ($template as $item){
            if ($item['template_id'] == $template_id){
                $template_content = $item['content'];
                break;
            }
        }
        //模板不存在
        if (!$template_content){
            throw new TemplateException(['msg'=>'消息模板不存在']);
        }
        $data = [
            "thing3" => $params["name"],
            "thing5"=> $params["message"]
        ];
        foreach ($data as $key=>$item){
            $template_content = str_replace("{{".$key.'.DATA}}',$item,$template_content);
            $data[$key] = ['value'=>$item];
        }
        //获取accountToken
        $access_token = $this->getAccessToken();
        //获取直播间对应用户标签
        $usertag = $this->user_tag();
        //100 福州直播间 101 莆田直播间
        $tagid = 101;
        foreach ($usertag as $value) {
            if (stripos($params["name"], $value) !== false) {
                $tagid = 100;
                break;
            }
        }
//        if (!$tagid) {
//            throw new TemplateException(['msg'=>'直播间信息不匹配']);
//        }
        $openid = User::field("openid")->where("groupid", "=", $tagid)->select()->toArray();
        if ($access_token){
//            $openid = $this->getTagUser($access_token, $tagid);
            foreach ($openid as $item){
                $result = $this->doSend($item["openid"],$template_id,$url,$data,$access_token,$miniprogram);
                $send_arr = [
                    "openid"=>$item["openid"],
                    "template_id"=>$template_id,
                    "content"=>$template_content,
                    "errcode"=>$result['errcode'],
                    "errmsg"=>$result['errmsg']
                ];
                Send::create($send_arr);
            }
        } else {
            throw new TemplateException(['msg'=>'getAccessToken失败']);
        }
        return true;
    }

    public function setTagUser()
    {
        //获取accountToken
        $access_token = $this->getAccessToken();
        //100 福州直播间 101 莆田直播间
        $tag_list = [101,100];
        //开启事务
        Db::startTrans();
        try {
            foreach ($tag_list as $value) {
                $openids = [];
                $openid = $this->getTagUser($access_token, $value);
                if ($openid["count"] == 0) {
                    continue;
                }
                $openidarr = $openid["data"]["openid"];
                foreach ($openidarr as $key => $open) {
                    $openids[$key] = $open;
                }
                User::where("openid", "in", $openids)->update(["groupid" => $value]);
            }
        }catch (Exception $e){
            Db::rollback();
        }
        Db::commit();
        return true;
    }

}
